#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>
#include "lisctl.h"
#include "wiringPi.h"
#include "myposix.h"

int main(int argc, char *argv[])
{   
    if(-1 == wiringPiSetup()){
        perror("wiringPiSetup error");
        return -1;
    }
    posix_pt msg = (posix_pt)malloc(sizeof(posix_node));
    if (NULL == msg)
    {
        perror("malloc error");
        return -1;
    }
    msg->pHead = NULL;
    msg->mqd = -1;
    msg->mqd = posix_create();
    if (-1 == msg->mqd)
    {
        perror("posix_create error");
        return -1;
    }

    msg->pHead = vo_add(msg->pHead);
    msg->pHead = tcp_add(msg->pHead);
    msg->pHead = fir_add(msg->pHead);
    msg->pHead = rec_add(msg->pHead);

    listen_pt tmp = msg->pHead;
    int cnt = 0;
    while (NULL != tmp)
    {
        tmp->init();  //调用对应的init函数，如果不加括号，则只是获取了init函数的地址
        tmp = tmp->next;
        cnt++;
    }
    pthread_t *tid = (pthread_t *)malloc(sizeof(pthread_t) * cnt);
    if (NULL == tid)
    {
        perror("malloc error");
        return -1;
    }
    tmp = msg->pHead;
    int i;
    for (i = 0; i < cnt; i++)
    {
        if (NULL != tmp)
        {
            pthread_create(&tid[i], NULL, tmp->get, (void *)msg);
            tmp = tmp->next;
        }
    }
    tmp = msg->pHead;
    for (i = 0; i < cnt; i++)
    {
        if (NULL != tmp)
        {
            pthread_join(tid[i], NULL);
            tmp = tmp->next;
        }
    }
    tmp = msg->pHead;
    for (i = 0; i < cnt; i++)
    {
        if (NULL != tmp)
        {
            tmp->final();   //调用对应的final函数,如果不加括号，则只是获取了final函数的地址
            tmp = tmp->next;
        }
    }
    posix_final(msg->mqd);
    free(msg);
    free(tid);
    return 0;
}